package framework.rpc.protocol.http.server;

import framework.rpc.protocol.http.dispatcher.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @author ldanniel
 */
public class HttpServer {
    //读取配置
    public  void start(String hostName, Integer port) {
        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(port);

        StandardEngine engine = new StandardEngine();
        engine.setDefaultHost(hostName);

        StandardHost host = new StandardHost();
        host.setName(hostName);

        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        //关键：向tomcat容器添加dispatcherServlet的servlet，DispatcherServlet需要很具接受的请求去匹配某个controller中的对应方法
        //SpringMVC中的DispatcherServlet，其中还有所有controller和注解，applicationContext就是所有Controller的所有的bean
        tomcat.addServlet(contextPath, "dispatcher",new DispatcherServlet());
        //接收的所有请求交给dispatcher处理
        context.addServletMappingDecoded("/*","dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
